package day02;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * @author Jetwang
 * @version 1.0
 * @since 2023/3/12 10:26
 * 从上到下打印二叉树 II
 */
public class Offer32 {


    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> lists = new ArrayList<>();
        if (root == null) {
            return lists;
        }
        LinkedList<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        int c1 = 1;
        while(!queue.isEmpty()) {
            List<Integer> list = new ArrayList<>();
            int c2 = 0;
            for (int i = 0; i < c1; i++) {
                TreeNode p = queue.poll();
                list.add(p.val);
                if (p.left != null) {
                    queue.offer(p.left);
                    c2++;
                }
                if (p.right != null) {
                    queue.offer(p.right);
                    c2++;
                }
            }
            lists.add(list);
            c1 = c2;
        }
        return lists;
    }
}
